#include "lvgl/lvgl.h"

void app_main(int argc, char* argv[]);

int main(int argc, char *argv[])
{
    lv_init();

    int32_t zoom_level = 100;
    bool allow_dpi_override = false;
    bool simulator_mode = false;
    lv_display_t* display = lv_windows_create_display(
        L"LVGL Window",
        480,
        320,
        zoom_level,
        allow_dpi_override,
        simulator_mode);
    if (!display)
    {
        return EXIT_FAILURE;
    }

    lv_lock();

    lv_indev_t* pointer_device = lv_windows_acquire_pointer_indev(display);
    if (!pointer_device)
    {
        return EXIT_FAILURE;
    }

    lv_indev_t* keypad_device = lv_windows_acquire_keypad_indev(display);
    if (!keypad_device)
    {
        return EXIT_FAILURE;
    }

    lv_indev_t* encoder_device = lv_windows_acquire_encoder_indev(display);
    if (!encoder_device)
    {
        return EXIT_FAILURE;
    }

    app_main(argc, argv);

    lv_unlock();

    while (1)
    {
        uint32_t time_till_next = lv_timer_handler();
        if(time_till_next == LV_NO_TIMER_READY) time_till_next = LV_DEF_REFR_PERIOD; /*handle LV_NO_TIMER_READY. Another option is to `sleep` for longer*/
        lv_delay_ms(time_till_next);
    }

    return EXIT_SUCCESS;
}

int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow)
{
    LPWSTR cmdLineW = GetCommandLineW();

    int argcW = 0;
    LPWSTR *argvW = CommandLineToArgvW(cmdLineW, &argcW);
    if (!argvW || argcW < 1) {
        return -1;
    }

    char **argv = (char**)malloc(argcW * sizeof(char*));
    if (!argv) {
        LocalFree(argvW);
        return -1;
    }

    for (int i = 0; i < argcW; ++i) {
        int size = WideCharToMultiByte(CP_UTF8, 0, argvW[i], -1, NULL, 0, NULL, NULL);
        argv[i] = (char*)malloc(size);
        if (!argv[i]) {
            for (int j = 0; j < i; ++j) free(argv[j]);
            free(argv);
            LocalFree(argvW);
            return -1;
        }
        WideCharToMultiByte(CP_UTF8, 0, argvW[i], -1, argv[i], size, NULL, NULL);
    }

    int ret = main(argcW, argv);

    for (int i = 0; i < argcW; ++i) {
        free(argv[i]);
    }
    free(argv);
    LocalFree(argvW);

    return ret;
}
